"use client"

import React, { useState, useEffect } from 'react'
import { AdminLayout } from '@/components/layout/admin-layout'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Modal } from '@/components/ui/modal'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Users,
  UserPlus,
  Search,
  Filter,
  RefreshCw,
  Eye,
  Edit,
  Trash2,
  MoreHorizontal
} from 'lucide-react'
import { adminAPI, type User } from '@/lib/api'
import { formatDateTime } from '@/lib/utils'
import { CompletePagination } from '@/components/ui/pagination'
import { useToast } from '@/components/ui/toast'
import { useConfirm } from '@/components/ui/confirm'

export default function UsersPage() {
  const [users, setUsers] = useState<User[]>([])
  const [loading, setLoading] = useState(true)
  const toast = useToast()
  const confirm = useConfirm()
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all')
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  // 添加用户模态框状态
  const [showAddModal, setShowAddModal] = useState(false)
  const [addUserForm, setAddUserForm] = useState({
    username: '',
    email: '',
    password: '',
    name: '',
    company: ''
  })
  const [submitting, setSubmitting] = useState(false)

  // 查看和编辑用户模态框状态
  const [showViewModal, setShowViewModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [selectedUser, setSelectedUser] = useState<User | null>(null)
  const [editUserForm, setEditUserForm] = useState({
    username: '',
    email: '',
    name: '',
    company: '',
    status: 1
  })

  useEffect(() => {
    const loadUsers = async () => {
      try {
        const usersData = await adminAPI.getAllUsers()
        setUsers(usersData)
      } catch (error) {
        console.error('加载用户失败:', error)
      } finally {
        setLoading(false)
      }
    }

    loadUsers()
  }, [])

  const filteredUsers = users.filter(user => {
    const matchesSearch = 
      user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (user.name && user.name.toLowerCase().includes(searchTerm.toLowerCase()))

    const matchesStatus = 
      statusFilter === 'all' ||
      (statusFilter === 'active' && user.status === 1) ||
      (statusFilter === 'inactive' && user.status === 0)

    return matchesSearch && matchesStatus
  })

  // 分页逻辑
  const totalItems = filteredUsers.length
  const totalPages = Math.ceil(totalItems / pageSize)
  const startIndex = (currentPage - 1) * pageSize
  const paginatedUsers = filteredUsers.slice(startIndex, startIndex + pageSize)

  const handlePageChange = (page: number) => {
    setCurrentPage(page)
  }

  const handlePageSizeChange = (newPageSize: number) => {
    setPageSize(newPageSize)
    setCurrentPage(1) // 重置到第一页
  }

  // 处理用户操作（查看、编辑、删除）
  const handleUserAction = async (action: string, userId: number) => {
    try {
      if (action === '查看') {
        const user = await adminAPI.getUserById(userId)
        setSelectedUser(user)
        setShowViewModal(true)
      } else if (action === '编辑') {
        const user = await adminAPI.getUserById(userId)
        setSelectedUser(user)
        setEditUserForm({
          username: user.username,
          email: user.email,
          name: user.name || '',
          company: user.company || '',
          status: user.status
        })
        setShowEditModal(true)
      } else if (action === '删除') {
        const confirmed = await confirm({
          title: '确认删除用户',
          message: '确认删除这个用户吗？此操作不可恢复！',
          type: 'danger',
          confirmText: '删除',
          cancelText: '取消'
        })
        
        if (confirmed) {
          await adminAPI.deleteUser(userId)
          // 重新加载用户列表
          const usersData = await adminAPI.getAllUsers()
          setUsers(usersData)
          toast.success('用户删除成功！')
        }
      }
    } catch (error) {
      console.error(`${action}用户失败:`, error)
      toast.error(`${action}用户失败，请重试`)
    }
  }

  // 处理添加用户表单变化
  const handleFormChange = (field: string, value: string) => {
    setAddUserForm(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 处理编辑用户表单变化
  const handleEditFormChange = (field: string, value: string | number) => {
    setEditUserForm(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 重置表单
  const resetForm = () => {
    setAddUserForm({
      username: '',
      email: '',
      password: '',
      name: '',
      company: ''
    })
  }

  // 重置编辑表单
  const resetEditForm = () => {
    setEditUserForm({
      username: '',
      email: '',
      name: '',
      company: '',
      status: 1
    })
  }

  // 处理添加用户
  const handleAddUser = async () => {
    if (!addUserForm.username || !addUserForm.email || !addUserForm.password) {
      toast.warning('请填写必填字段：用户名、邮箱、密码')
      return
    }

    setSubmitting(true)
    try {
      // 调用API添加用户
      await adminAPI.createUser(addUserForm)
      
      // 成功后重新加载用户列表
      const usersData = await adminAPI.getAllUsers()
      setUsers(usersData)
      
      // 关闭模态框并重置表单
      setShowAddModal(false)
      resetForm()
      
      toast.success('用户添加成功！')
    } catch (error) {
      console.error('添加用户失败:', error)
      toast.error('添加用户失败，请重试')
    } finally {
      setSubmitting(false)
    }
  }

  // 处理编辑用户
  const handleEditUser = async () => {
    if (!editUserForm.username || !editUserForm.email) {
      toast.warning('请填写必填字段：用户名、邮箱')
      return
    }

    if (!selectedUser) return

    setSubmitting(true)
    try {
      // 调用API更新用户
      await adminAPI.updateUser(selectedUser.id, editUserForm)
      
      // 重新加载用户列表
      const usersData = await adminAPI.getAllUsers()
      setUsers(usersData)
      
      // 关闭模态框并重置表单
      setShowEditModal(false)
      resetEditForm()
      setSelectedUser(null)
      
      toast.success('用户更新成功！')
    } catch (error) {
      console.error('更新用户失败:', error)
      toast.error('更新用户失败，请重试')
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) {
    return (
      <AdminLayout>
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <h1 className="text-2xl font-bold text-gray-900">用户管理</h1>
          </div>
          <div className="text-center py-12">加载中...</div>
        </div>
      </AdminLayout>
    )
  }

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* Page Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">用户管理</h1>
            <p className="text-gray-600">管理和监控平台用户</p>
          </div>
          <Button onClick={() => setShowAddModal(true)}>
            <UserPlus className="h-4 w-4 mr-2" />
            添加用户
          </Button>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">总用户数</p>
                  <p className="text-2xl font-bold text-gray-900">{users.length}</p>
                </div>
                <Users className="h-8 w-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">活跃用户</p>
                  <p className="text-2xl font-bold text-gray-900">
                    {users.filter(u => u.status === 1).length}
                  </p>
                </div>
                <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                  <Users className="h-5 w-5 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">禁用用户</p>
                  <p className="text-2xl font-bold text-gray-900">
                    {users.filter(u => u.status === 0).length}
                  </p>
                </div>
                <div className="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
                  <Users className="h-5 w-5 text-red-600" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">近期登录</p>
                  <p className="text-2xl font-bold text-gray-900">
                    {users.filter(u => u.lastLoginTime).length}
                  </p>
                </div>
                <div className="w-8 h-8 bg-amber-100 rounded-full flex items-center justify-center">
                  <Users className="h-5 w-5 text-amber-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Filters and Search */}
        <Card>
          <CardContent className="p-6">
            <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
              <div className="flex flex-1 gap-4">
                <div className="relative flex-1 max-w-sm">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                  <input
                    type="text"
                    placeholder="搜索用户..."
                    className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                  />
                </div>
                <select
                  className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value as any)}
                >
                  <option value="all">全部状态</option>
                  <option value="active">正常</option>
                  <option value="inactive">禁用</option>
                </select>
              </div>
              <div className="flex gap-2">
                <Button variant="outline" size="sm">
                  <Filter className="h-4 w-4 mr-2" />
                  筛选
                </Button>
                <Button variant="outline" size="sm" onClick={() => window.location.reload()}>
                  <RefreshCw className="h-4 w-4 mr-2" />
                  刷新
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Users Table */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Users className="h-5 w-5" />
                <span>用户列表 (共 {totalItems} 条记录)</span>
              </div>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>用户信息</TableHead>
                  <TableHead>联系方式</TableHead>
                  <TableHead>公司信息</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>注册时间</TableHead>
                  <TableHead>最后登录</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {paginatedUsers.length > 0 ? (
                  paginatedUsers.map((user) => (
                    <TableRow key={user.id}>
                      <TableCell>
                        <div className="flex items-center space-x-3">
                          <div className="w-10 h-10 bg-slate-600 text-white rounded-full flex items-center justify-center">
                            <span className="text-sm font-medium">
                              {user.name ? user.name.charAt(0) : user.username.charAt(0)}
                            </span>
                          </div>
                          <div>
                            <div className="font-medium text-gray-900">{user.name || user.username}</div>
                            <div className="text-sm text-gray-500">ID: {user.id}</div>
                            <div className="text-sm text-gray-500">{user.username}</div>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm">
                          <div>{user.email}</div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm text-gray-600">
                          {user.company || '未设置'}
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant={user.status === 1 ? 'default' : 'destructive'}
                          className={user.status === 1 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}
                        >
                          {user.status === 1 ? '正常' : '禁用'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm text-gray-600">
                          {formatDateTime(user.createdAt)}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm text-gray-600">
                          {user.lastLoginTime 
                            ? formatDateTime(user.lastLoginTime)
                            : '从未登录'
                          }
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleUserAction('查看', user.id)}
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleUserAction('编辑', user.id)}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleUserAction('删除', user.id)}
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-8">
                      <div className="text-gray-500">
                        {searchTerm || statusFilter !== 'all' ? '没有找到匹配的用户' : '暂无用户数据'}
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        {/* Pagination */}
        {totalItems > 0 && (
          <Card>
            <CardContent className="p-6">
              <CompletePagination
                currentPage={currentPage}
                totalPages={totalPages}
                totalItems={totalItems}
                pageSize={pageSize}
                onPageChange={handlePageChange}
                onPageSizeChange={handlePageSizeChange}
                pageSizeOptions={[10, 20, 50, 100]}
              />
            </CardContent>
          </Card>
        )}

        {/* Add User Modal */}
        <Modal
          isOpen={showAddModal}
          onClose={() => {
            setShowAddModal(false)
            resetForm()
          }}
          title="添加新用户"
          footer={
            <div className="flex justify-end space-x-2">
              <Button 
                variant="outline" 
                onClick={() => {
                  setShowAddModal(false)
                  resetForm()
                }}
                disabled={submitting}
              >
                取消
              </Button>
              <Button 
                onClick={handleAddUser}
                disabled={submitting}
              >
                {submitting ? '添加中...' : '添加用户'}
              </Button>
            </div>
          }
        >
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                用户名 <span className="text-red-500">*</span>
              </label>
              <Input
                value={addUserForm.username}
                onChange={(e) => handleFormChange('username', e.target.value)}
                placeholder="请输入用户名"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                邮箱 <span className="text-red-500">*</span>
              </label>
              <Input
                type="email"
                value={addUserForm.email}
                onChange={(e) => handleFormChange('email', e.target.value)}
                placeholder="请输入邮箱地址"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                密码 <span className="text-red-500">*</span>
              </label>
              <Input
                type="password"
                value={addUserForm.password}
                onChange={(e) => handleFormChange('password', e.target.value)}
                placeholder="请输入密码"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                姓名
              </label>
              <Input
                value={addUserForm.name}
                onChange={(e) => handleFormChange('name', e.target.value)}
                placeholder="请输入真实姓名"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                公司
              </label>
              <Input
                value={addUserForm.company}
                onChange={(e) => handleFormChange('company', e.target.value)}
                placeholder="请输入公司名称"
                disabled={submitting}
              />
            </div>
          </div>
        </Modal>

        {/* View User Modal */}
        <Modal
          isOpen={showViewModal}
          onClose={() => {
            setShowViewModal(false)
            setSelectedUser(null)
          }}
          title="查看用户详情"
          footer={
            <div className="flex justify-end">
              <Button onClick={() => setShowViewModal(false)}>关闭</Button>
            </div>
          }
        >
          {selectedUser && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">用户ID</label>
                  <div className="text-sm text-gray-900">{selectedUser.id}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                  <div className="text-sm text-gray-900">{selectedUser.username}</div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                  <div className="text-sm text-gray-900">{selectedUser.email}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">真实姓名</label>
                  <div className="text-sm text-gray-900">{selectedUser.name || '未设置'}</div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">公司</label>
                  <div className="text-sm text-gray-900">{selectedUser.company || '未设置'}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">状态</label>
                  <div className="text-sm">
                    <Badge
                      variant={selectedUser.status === 1 ? 'default' : 'destructive'}
                      className={selectedUser.status === 1 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}
                    >
                      {selectedUser.status === 1 ? '正常' : '禁用'}
                    </Badge>
                  </div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">注册时间</label>
                  <div className="text-sm text-gray-900">{formatDateTime(selectedUser.createdAt)}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">最后登录</label>
                  <div className="text-sm text-gray-900">
                    {selectedUser.lastLoginTime ? formatDateTime(selectedUser.lastLoginTime) : '从未登录'}
                  </div>
                </div>
              </div>
            </div>
          )}
        </Modal>

        {/* Edit User Modal */}
        <Modal
          isOpen={showEditModal}
          onClose={() => {
            setShowEditModal(false)
            resetEditForm()
            setSelectedUser(null)
          }}
          title="编辑用户"
          footer={
            <div className="flex justify-end space-x-2">
              <Button 
                variant="outline" 
                onClick={() => {
                  setShowEditModal(false)
                  resetEditForm()
                  setSelectedUser(null)
                }}
                disabled={submitting}
              >
                取消
              </Button>
              <Button 
                onClick={handleEditUser}
                disabled={submitting}
              >
                {submitting ? '保存中...' : '保存更改'}
              </Button>
            </div>
          }
        >
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                用户名 <span className="text-red-500">*</span>
              </label>
              <Input
                value={editUserForm.username}
                onChange={(e) => handleEditFormChange('username', e.target.value)}
                placeholder="请输入用户名"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                邮箱 <span className="text-red-500">*</span>
              </label>
              <Input
                type="email"
                value={editUserForm.email}
                onChange={(e) => handleEditFormChange('email', e.target.value)}
                placeholder="请输入邮箱地址"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                真实姓名
              </label>
              <Input
                value={editUserForm.name}
                onChange={(e) => handleEditFormChange('name', e.target.value)}
                placeholder="请输入真实姓名"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                公司
              </label>
              <Input
                value={editUserForm.company}
                onChange={(e) => handleEditFormChange('company', e.target.value)}
                placeholder="请输入公司名称"
                disabled={submitting}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                状态
              </label>
              <select
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                value={editUserForm.status}
                onChange={(e) => handleEditFormChange('status', parseInt(e.target.value))}
                disabled={submitting}
              >
                <option value={1}>正常</option>
                <option value={0}>禁用</option>
              </select>
            </div>
          </div>
        </Modal>
      </div>
    </AdminLayout>
  )
}